package com.springx.examples.showcase.service;

import com.springx.examples.showcase.entity.RoleResource;
import com.springx.examples.showcase.repository.mybatis.RoleResourceMapper;
import com.springx.modules.utils.Exceptions;
import com.springx.starter.utils.ConvertUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by roman_000 on 2015/8/23.
 */
@Service
@Transactional
public class RoleResourceService extends BaseService<RoleResource> {
    @Autowired
    private RoleResourceMapper roleResourceMapper;

    public void insert(Long roleId, List<HashMap<String, Object>> checkParams) {
        if (CollectionUtils.isNotEmpty(checkParams)) {
            RoleResource roleResource;
            for (Map<String, Object> map : checkParams) {
                Long id = ConvertUtils.convert2Long(map.get("id"));
                Boolean checked = ConvertUtils.convert2Boolean(map.get("checked"));
                if (checked) {
                    roleResource = new RoleResource();
                    roleResource.setRoleId(roleId);
                    roleResource.setResourceId(id);
                    try {
                        roleResourceMapper.insert(roleResource);
                    } catch (DuplicateKeyException ex) {//键冲突的异常,可以继续
                        logger.info(Exceptions.getStackTraceAsString(ex));
                    }
                } else {
                    roleResourceMapper.deleteByPrimaryKey(id);
                }
            }
        }
    }
}
